package sany.iec.service.svg01;

import com.serotonin.modbus4j.exception.IllegalDataAddressException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import sany.iec.common.GlobalConstant;
import sany.iec.config.ModbusSVG01Server;
import sany.iec.utils.DataParseUtil;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @Author : 托马斯
 * @Date : 2025/7/3 11:39
 * @Description :
 */
@Service
@Slf4j
@DependsOn("svg01DataService")
public class Svg01Schedule {

    @Value("${modbus.svg01.install}")
    private Double svgInstall;

    @Resource
    private Svg01DataService svgDataService;

    @Resource
    private ModbusSVG01Server modbusSVGSalveConfig;

    @PostConstruct
    public void init() {
        // 初始化数据
        log.info("开始进行SVG01数据初始化~~~~");
        // 初始化上下限
        Short[] nums = DataParseUtil.getNumsFromFloatCDAB(svgInstall.floatValue());
        svgDataService.setHoldingRegister(710, nums[0]);
        svgDataService.setHoldingRegister(711, nums[1]);
        nums = DataParseUtil.getNumsFromFloatCDAB(svgInstall.floatValue() * -1);
        svgDataService.setHoldingRegister(712, nums[0]);
        svgDataService.setHoldingRegister(713, nums[1]);

        svgDataService.setHoldingRegister(820, (short) 1);
        // SVG 投入与退出信号
        svgDataService.setHoldingRegister(832, (short) 1);
    }

    @Scheduled(initialDelay = 5000, fixedRate = 3000)
    public void insertData() throws IllegalDataAddressException {
        Short AB = svgDataService.getHoldingRegister(3106);
        Short CD = svgDataService.getHoldingRegister(3107);
        Float v = DataParseUtil.getFloatCDAB(AB, CD);
        // SVG无功指令进行存储
        GlobalConstant.SVG_VALUE = v;
        svgDataService.setHoldingRegister(202, AB);
        svgDataService.setHoldingRegister(203, CD);
        svgDataService.setHoldingRegister(212, AB);
        svgDataService.setHoldingRegister(213, CD);

        log.info("SVG01 无功指令: {}  实发无功: {}   投入与退出: {}", DataParseUtil.getFloatCDAB(svgDataService.getHoldingRegister(3106), svgDataService.getHoldingRegister(3107)),
                DataParseUtil.getFloatCDAB(svgDataService.getHoldingRegister(202), svgDataService.getHoldingRegister(203)), svgDataService.getHoldingRegister(832));
    }

}
